package org.example.api;

import org.example.dao.UserDao;
import org.example.model.User;
import org.example.util.WebUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //构造一个返回数据(ok: boolean, error: String)
        Map<String, Object> body = new HashMap<>();

        //处理请求：json数据转为Java对象(请求正文包含中文，记得设置编码)
        req.setCharacterEncoding("UTF-8");
        //json转Java对象
        User user = WebUtil.deserialize(req, User.class);

        //验证账号密码：先根据账号查询，结果是一条或没有数据
        User query = UserDao.queryByUsername(user.getUsername());
        //根据账号查不到数据，说明账号不存在
        if(query == null){
            body.put("ok", false);
            body.put("error", "账号不存在");
            //用户输入的密码和查询的用户密码不一样
        }else if(!query.getPassword().equals(user.getPassword())){
            body.put("ok", false);
            body.put("error", "账号或密码错误");
            //验证通过
        }else{
            body.put("ok", true);
            //登录成功，创建session，并保存用户信息
            HttpSession session = req.getSession();//创建session
            //在session中保存用户信息：保存数据库查询的用户，信息比较全
            session.setAttribute("user", query);
        }
        //返回响应：Java对象序列化为json字符串，写入响应正文
        WebUtil.serialize(resp, body);
    }
}